<?php
/**
 * Classe em construção
 * Função desta classe gerar imagens em tempo de execução, imagens estas que não serão salvas.
 * 
 * @author Cristiano M. Gomes <cmgomes.es@gmail.com>
 * @ignore Classe não completamente implementada
 */
class CPImagem{

	private $x = 0;
	private $y = 40;
	private $margin_top = 40;
	private $size = 24;
	private $letter_width = 16;
	private $letter_height = 40;
	private $MAX_WIDTH = 600;
	private $font_file = "../../web/font/VAGRON_0.TTF"; //VAGROUN2.TTF VAGROLN.TTF

	public static function gerar_imagem(){
		if (!file_exists($this->font_file)) {
	    	echo "Font não encontrada"; exit();
		}

		$texts = array();
		$text =  (array_key_exists('text', $_GET)) ? $_GET['text'] : '';

		$width = strlen($text) * $this->letter_width;
		$height = 50;

		if ($width > $this->MAX_WIDTH) {
		    $width = $this->MAX_WIDTH;
		    $words = explode(" ", $text);
		    $line = array();
		    foreach ($words as $word) {
		        if (strlen(join(" ", $line) . " " . $word) * $this->letter_width < $this->MAX_WIDTH) {
		            $line[] = $word;
		        } else {
		            $texts[] = join(" ", $line);
		            $line = array($word);
		        }
		    }
		    if (strlen(join("", $line)) > 0) {
		        $texts[] = join(" ", $line);
		    }
		    $height = sizeof($texts) * $this->size + $this->letter_height;
		} else {
		    $width += $this->letter_width;
		    $texts[] = $text;
		}

		$image = imagecreatetruecolor($width, $height);
		$nimage = imagecreatefrompng('../../../midia/img/fundo.png');
		imagecopy($image,$nimage,0, 0, 0, 0, $width, $height);

		foreach ($texts as $text) {
		    $font_color = imagecolorallocate($image, 13, 63, 130);
		    imagettftext($image, $this->size, 0, $this->x, $this->y, $font_color, $this->font_file, $text);

		    $font_color = imagecolorallocate($image, 255, 255, 255);
		    imagettftext($image, $this->size, 0, $this->x, $this->y - 1, $font_color, $this->font_file, $text);

		    $y += $this->margin_top;
		}

		header('Content-type: image/png');
		imagepng($image);
		imagedestroy($image);
	}
}